package com.dp.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dp.common.domain.dto.Result;
import com.dp.common.domain.dto.UserDTO;
import com.dp.common.utils.RegexUtils;
import com.dp.user.domain.dto.LoginFormDTO;
import com.dp.user.domain.po.User;
import com.dp.user.mapper.UserMapper;
import com.dp.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static com.dp.common.constants.RedisConstants.*;
import static com.dp.common.constants.SystemConstants.*;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone) {
        // 校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        // 生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 记录验证码
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        log.debug("发送短信验证码成功，验证码：{}", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        // 校验手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号格式错误！");
        }
        // 校验验证码
        if (loginForm.getCode() != null) {
            String cacheCode  = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());
            if (cacheCode == null || !cacheCode.equals(loginForm.getCode())) {
                return Result.fail("验证码错误！");
            }
        }
        // 查询用户是否存在
        User user = query().eq("phone", loginForm.getPhone()).one();
        if (user == null) {
            user = createUserWithPhone(loginForm.getPhone());
        }
        String token = UUID.randomUUID().toString(true);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 保存用户信息到redis
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token, BeanUtil.beanToMap(userDTO, new HashMap<>()
        , CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((name, value) -> value.toString())));
        stringRedisTemplate.expire(LOGIN_USER_KEY+token, LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
